package com.atguigu.crowd.mvc.handler;

import com.atguigu.crowd.entity.Menu;
import com.atguigu.crowd.service.api.MenuService;
import com.atguigu.crowd.util.ResultEntity;
import com.sun.tools.javac.comp.MemberEnter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

@Controller
public class MenuHandler {

    @Autowired
    private MenuService menuService;

    @RequestMapping("/menu/remove.json")
    @ResponseBody
    public ResultEntity<String> removeMenu(Integer id){
        menuService.removeMenu(id);


        return ResultEntity.successWithoutData();
    }

    @RequestMapping("/menu/update.json")
    @ResponseBody
    public ResultEntity<String> updateMenu(Menu menu){
        menuService.updateMenu(menu);

        return ResultEntity.successWithoutData();
    }
    @RequestMapping("/menu/save.json")
    @ResponseBody
    public ResultEntity<String> saveMenu(Menu menu){
        menuService.saveMenu(menu);


        return ResultEntity.successWithoutData();
    }

    @RequestMapping("/menu/get/whole/tree.json")
    @ResponseBody
    public ResultEntity<Menu> getWholeTreeNew(){
        List<Menu> menuList = menuService.getAll();

//       存储根节点
        Menu root=null;

        //存储父节点的map集合
        Map<Integer, Menu> menuMap = new HashMap<>();

//        遍历menuList填充menuMap
        for (Menu menu:menuList){
            Integer id = menu.getId();
            menuMap.put(id,menu);
        }
        // 5.再次遍历 menuList 查找根节点、组装父子节点
        for (Menu menu:menuList){
//            获取当前节点的pid
            Integer pid = menu.getPid();
            if (pid==null){
                root=menu;

                continue;
            }
            // 9.如果 pid 不为 null，说明当前节点有父节点，那么可以根据 pid 到 menuMap 中 查找对应的 Menu 对象

            Menu father = menuMap.get(pid);

            //将子节点存入父节点的集合
            father.getChildren().add(menu);

        }
        return ResultEntity.successWithoutData(root);




    }


    public ResultEntity<Menu> getWholeTreeOld(){
//        获取所有的菜单列表
        List<Menu> menuList = menuService.getAll();

        //存放找到的根节点
        Menu root=null;

        //遍历出所有父节点
        for (Menu menu:menuList){
            Integer pid = menu.getPid();


            //根据pId判断是否为父节点
            if (pid==null){


                root=menu;

                //结束当前循环
                continue;

            }
            for (Menu myFathMenu:menuList) {
                Integer id = myFathMenu.getId();

                //根据根据地的id和子节点的pid进行比较，相等进行组装
                if (Objects.equals(pid, id)) {
                    myFathMenu.getChildren().add(menu);
                    break;
                }
            }
        }
        return ResultEntity.successWithoutData(root);


    }
}
